from datetime import datetime
from flask import render_template,session,redirect,url_for,request
from flask_login import login_required

from . import main
from .forms import NameForm,NewsForm
from .common import *
from .. import db
from ..models import User,News

@main.route('/',methods=['GET','POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        return redirect(url_for('.index'))

    return render_template('index.html')

@main.route('/add_news',methods=['GET','POST'])
@login_required
def add_news():
    form = NewsForm()
    if form.validate_on_submit():
        news = News(title=form.title.data,
                    imgUrl=form.imgUrl.data,
                    digest=form.digest.data,
                    content=form.content.data,
                    type=form.type.data,
                    pubTime=form.pubTime.data,
                    publisher=form.publisher.data)
        db.session.add(news)
        db.session.commit()
        return redirect(url_for('.add_news'))

    return render_template('add_news.html',form=form)

@main.route('/delete_news',methods=['GET','POST'])
@login_required
def delete_news():
    nid = request.args.get('nid',0,type=int)
    if nid == 0:
        return redirect(url_for('.delete_news'))

    news_item = News.query.filter_by(nid=nid).first()
    db.session.delete(news_item)
    db.session.commit()
    return redirect(url_for('.manage_news'))


@main.route('/manage_news',methods=['GET','POST'])
@login_required
def manage_news():
    page = request.args.get('page',1,type=int)
    pagination = News.query.order_by(-News.pubTime).paginate(page,per_page=10,error_out=False)

    news = pagination.items

    return render_template('manage_news.html',news=news,pagination=pagination)

@main.route('/manage_launch_img',methods=['GET','POST'])
@login_required
def manage_launch_img():
    img_url = get_launch_img()
    return render_template('manage_launch_img.html',img_url=img_url)

@main.route('/upload_launch_img',methods=['GET','POST'])
@login_required
def upload_launch_img():
    if request.method=='POST':
        try:
            save_launch_img(request.form['new_img_url'])
        except Exception as e:
            print('save launch img error:',e)

    return redirect(url_for('.manage_launch_img'))
